<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Roster extends Base {
	// construct
	public function run() {
		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func) = $this->uri;
			$this->$func();
		} else $this->index();
	}

	// indexxx
	public function index() {
		$this->view->func = 'index';

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Realm Status';

		// get guild
		$guild = $this->db->querySingle("SELECT value FROM blizzard WHERE api = 'guild'");
		if(is_null($guild))
			die(new Error());

		// get average ilevel
		$average = $this->db->querySingle("SELECT value FROM blizzard WHERE api = 'average'");
		$ilevel = $average ? unserialize($average) : array();

		// data
		$this->view->guild = unserialize($guild);

		// set side
		$this->view->side = array(
			0 => '<span class="Alliance">%s</span>',
			1 => '<span class="Horde">%s</span>'
		);

		// set updated
		$this->view->updated = Helper::format_time(floor($this->view->guild->lastModified / 1000));

		// set class
		$classes = array(
			1 => 'Warrior',
			2 => 'Paladin',
			3 => 'Hunter',
			4 => 'Rogue',
			5 => 'Priest',
			6 => 'Death Knight',
			7 => 'Shaman',
			8 => 'Mage',
			9 => 'Warlock',
			10 => 'Monk',
			11 => 'Druid'
		);

		// ranks from settings
		$this->view->ranks = explode(', ', $this->settings['rank_terminology']);

		// go through each member
		$characters = array();
		foreach($this->view->guild->members as $one) {
			// search fpr character in users table
			$name = $this->db->escapeString(strtolower($one->character->name));
			$apply = $this->db->escapeString($this->settings['rank_apply']);
			$result = $this->db->querySingle("SELECT id, name, email FROM users WHERE lower(name) = '{$name}' AND rank != '{$apply}'", true);

			// build array
			$characters[] = array(
				'user' => !$result ? false : array(
					'id' => $result['id'],
					'link' => $result['id'] . '-' . Helper::generate_named_id($result['name']),
					'name' => $result['name'],
					'avatar' => md5(strtolower($result['email']))
				),
				'name' => $one->character->name,
				'rank' => $one->rank,
				'level' => $one->character->level,
				'average' => isset($ilevel[strtolower($one->character->name)]) ? $ilevel[strtolower($one->character->name)] : 'Unknown',
				'role' => isset($one->character->spec->role) ? $one->character->spec->role : 'Unknown',
				'spec' => isset($one->character->spec->name) ? $one->character->spec->name : 'Unknown',
				'class' => $classes[$one->character->class],
				'picture' => $one->character->thumbnail,
			);
		}

		// send to view
		$this->view->characters = $characters;
	}

	// update character ilevel
	public function update() {
		// get vars
		$realm = $this->request->post('realm');
		$name = $this->request->post('name');
		$data = $this->request->post('data');
		if(is_null($realm) || is_null($name) || is_null($data))
			return $this->json = array('success' => false);

		// realm not correct?
		if($realm != strtolower($this->settings['blizz_realm']))
			return $this->json = array('success' => false);

		// get data
		$list = array();
		$data = json_decode($data);
		foreach($data->items as $item => $data)
			if($item != 'shirt' && $item != 'tabard' && $item != 'averageItemLevel' && $item != 'averageItemLevelEquipped')
				$list[] = $data->itemLevel;

		// somehow we got no list?
		if(!count($list) > 0)
			return $this->json = array('success' => false);

		// calculate average item level
		$average = sprintf('%.3f', round(array_sum($list) / count($list), 3));

		// get averages
		$save = array();
		$ilevel = $this->db->querySingle("SELECT value FROM blizzard WHERE api = 'average'");
		if(!is_null($ilevel))
			$save = unserialize($ilevel);

		// save averages
		$save[$name] = $average;
		$data = $this->db->escapeString(serialize($save));
		if(is_null($ilevel)) $this->db->exec("INSERT INTO blizzard (api, value, time) VALUES ('average', '{$data}', '". time() ."')");
		else $this->db->exec("UPDATE blizzard SET value='{$data}', time='". time() ."' WHERE api = 'average'");

		// return number
		return $this->json = array('success' => true, 'ilevel' => $average);
	}
}